<template>
  <div id="userPassport">
    <a-form
      :style="{ maxWidth: 480, margin: '0 auto' }"
      label-align="left"
      :model="formState"
      name="basic"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 22 }"
      autocomplete="off"
      @finish="handleSubmit"
    >
      <a-form-item
        label="手机号"
        name="phone"
        :rules="[
          { required: true, message: '请输入手机号' },
          { min: 11, max: 11, message: '请输入正确的手机号' },
        ]"
      >
        <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码长度不能小于8位' },
        ]"
      >
        <a-input-password
          v-model:value="formState.password"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item
        :wrapper-col="{ offset: 4, span: 16 }"
        style="text-align: center"
      >
        <a-button type="primary" html-type="submit" class="remit-button">
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
import { useLoginUserStore } from "@/store/useLoginUserStore";
import { userLogin } from "@/api/user";
import { message } from "ant-design-vue";
import { useAuthStore } from "@/store/useLoginUserStore";
import { useRouter } from "vue-router";

interface FormState {
  phone: string;
  password: string;
}

const formState = reactive<FormState>({
  phone: "",
  password: "",
});

const authStore = useAuthStore();
const userLoginStore = useLoginUserStore();
const router = useRouter();
const handleSubmit = async (values: FormState) => {
  try {
    const res = await userLogin(values);
    console.log("检查token在哪", res);
    if (res.data.code === 200) {
      userLoginStore.setLoginUser(res.data);
      const token = res.data.data.tokenValue;
      console.log("检查token", token);
      localStorage.setItem("token", token);
      await userLoginStore.fetchLoginUser();
      message.success("登录成功");
      router.push({ path: "/hot" });
      window.location.reload();
      authStore.closeLoginModal();
    } else {
      message.error("手机号或密码错误");
    }
  } catch (error) {
    console.log("登陆异常", error);
  }
};
</script>

<style scoped>
#userPassport .title {
  text-align: center;
  margin-bottom: 16px;
}

#userPassport .text-p {
  text-align: center;
  margin-bottom: 16px;
}
</style>
